<?php
/**
 * 默认展示页面
 *
 *

 * @copyright  Copyright (c) 2014-2015 TuntronKJ Inc. (http://www.tuntron.com)
 * @license    http://www.tuntron.com
 * @link       http://www.tuntron.com
 * @since      File available since Release v1.1
 */
defined('InTuntronKJ') or exit('Access Invalid!');

/**
 * Class BettingControl
 */
class BettingControl extends BaseLotteryHallControl{

	public function indexOp(){
		//最近开奖记录
		$model_data = Model('data_class');
		$model_play = Model('played');
		
		$param = array(
			'type' => 1,					
		);
		$data = $model_data->getList($param,'',5);

		$kaijiang_list = array();
		if(!empty($data) && is_array($data)){
			foreach($data as $key=>$item){
				$kaijiang_list[$key]['qihao'] = $item['number'];
				$hao = explode(',',$item['data']);
				
				$kaijiang_list[$key]['hao'] = $hao;
				
				if(end($hao)>=5){
					$kaijiang_list[$key]['dx'] = '大';
				}else{
					$kaijiang_list[$key]['dx'] = '小';
				}
				
				if(end($hao)%2 == 0){
					$kaijiang_list[$key]['ds'] = '双';	
				}else{
					$kaijiang_list[$key]['ds'] = '单';
				}
			}
		}
		
		$played_group = $model_play->getGroupList(array('type'=>1,'enable'=>1));	

		$played_list = array();
		foreach($played_group as $key=>$val){
			$played = $model_play->getPlayList(array('groupId'=>$val['id'],'enable'=>1));
			foreach($played as $k=>$item){
				$ids_str = $item['id'].','.$ids_str;
			}
			$ids_str = substr($ids_str,0,strlen($ids_str)-1);
			$played_group[$key]['ids'] = $ids_str;
			$played_list[$key] = $played;
			$ids_str = "";
		}
		
		$played_all_list = $model_play->getPlayList(array('type'=>1,'enable'=>1));			//类型为时时彩的所有玩法列表

		$param['curBetType'] = $played_group[0]['id'];
		$param['curBetTypeName'] = $played_group[0]['groupName'];
		$param['lotteryId'] = 1;
		
		Tpl::output('played_all_list',$played_all_list);
		Tpl::output('played_list',$played_list);
		Tpl::output('played_group',$played_group);
		Tpl::output('kaijiang_list',$kaijiang_list);
		Tpl::output('param',$param);
		Tpl::showpage('Betting');
	}

	//奖金与赔率
	public function SetUserReturnPointOp(){
		print_r($_POST);exit;
	}
	
	//玩法模板
	public function GetPlayedTplOp(){
		$model_play = Model('played');
		$model_bet = Model('bat');

		$playId = $_POST['playId'];
		
		$playInfo = $model_play->getPlayInfo(array('id'=>$playId));
// 		Tpl::showpage('game-played/'.$playInfo['playedTpl']);

		$regex = array(
			'allSelect1'	=> "[0-9]{1,10}|[0-9]{1,10}|[0-9]{1,10}|[0-9]{1,10}|[0-9]{1,10}",
			'allSelect2'	=> "[0-9]{1,10}|[0-9]{1,10}|[0-9]{1,10}|[0-9]{1,10}",
			'allSelect3'	=> "[0-9]{1,10}|[0-9]{1,10}|[0-9]{1,10}",
			'allSelect4'	=> "[0-9]{1,10}|[0-9]{1,10}",
			'sccInput1'		=> "[0-9][0-9][0-9][0-9][0-9]",
			'sccInput2'		=> "[0-9][0-9][0-9][0-9]",
			'sccInput3'		=> "[0-9][0-9][0-9]",
			'sccInput4'		=> "[0-9][0-9]",
			'permutaions2'	=> "[0-9]{2,10}",
			'permutaions3'	=> "[0-9]{3,10}",
			'combine2'		=> "[0-9]{2,10}",
			'combine3'		=> "[0-9]{3,10}",
				
		);
		
		
		$data = array();
		switch($playId){
			case "2":
				$data['panel'] = "0,1,2,3,4";	
				$data['selectedregex'] = $regex['allSelect1'];					
				$data['matchtype'] = "allSelect";
				break;
			case "3":
				$data['panel'] = "";
				$data['selectedregex'] = $regex['sccInput1'];
				$data['matchtype'] = "sccInput";
				break;
			case "4":
				$data['panel'] = "0,1,2,3";
				$data['selectedregex'] = $regex['allSelect2'];
				$data['matchtype'] = "allSelect";
				break;
			case "5":
				$data['panel'] = "";
				$data['selectedregex'] = $regex['sccInput2'];
				$data['matchtype'] = "sccInput";
				break;
			case "6":
				$data['panel'] = "1,2,3,4";
				$data['selectedregex'] = $regex['allSelect2'];
				$data['matchtype'] = "allSelect";
				break;
			case "7":
				$data['panel'] = "";
				$data['selectedregex'] = $regex['sccInput2'];
				$data['matchtype'] = "sccInput";
				break;
			case "8":
				$data['panel'] = "0,1,2,3,4";
				$data['selectedregex'] = $regex['allSelect2'];
				$data['matchtype'] = "allSelect";
				break;
			case "9":
				$data['panel'] = "";
				$data['selectedregex'] = $regex['sccInput2'];
				$data['matchtype'] = "sccWeiInput";
				break;
			case "10":
				$data['panel'] = "0,1,2";
				$data['selectedregex'] = $regex['allSelect3'];
				$data['matchtype'] = "allSelect";
				break;
			case "11":
				$data['panel'] = "";
				$data['selectedregex'] = $regex['sccInput3'];
				$data['matchtype'] = "sccInput";
				break;
			case "12":
				$data['panel'] = "2,3,4";
				$data['selectedregex'] = $regex['allSelect3'];
				$data['matchtype'] = "allSelect";
				break;
			case "13":
				$data['panel'] = "";
				$data['selectedregex'] = $regex['sccInput3'];
				$data['matchtype'] = "sccInput";
				break;
			case "14":
				$data['panel'] = "0,1,2,3,4";
				$data['selectedregex'] = $regex['allSelect3'];
				$data['matchtype'] = "allSelect";
				break;
			case "15":
				$data['panel'] = "";
				$data['selectedregex'] = $regex['sccInput2'];
				$data['matchtype'] = "sccWeiInput";
				break;
			case "16":
				$data['panel'] = "5";
				$data['selectedregex'] = $regex['combine2'];
				$data['matchtype'] = "combine";
				break;
			case "17":
				$data['panel'] = "5";
				$data['selectedregex'] = $regex['combine3'];
				$data['matchtype'] = "combine";
				break;
			case "18":
				$data['panel'] = "5";
				$data['selectedregex'] = $regex['sccInput3'];
				$data['matchtype'] = "scczxInput";
				break;
			case "19":
				$data['panel'] = "5";
				$data['selectedregex'] = $regex['combine2'];
				$data['matchtype'] = "combine";
				break;
			case "20":
				$data['panel'] = "5";
				$data['selectedregex'] = $regex['combine3'];
				$data['matchtype'] = "combine";
				break;
			case "21":
				$data['panel'] = "5";
				$data['selectedregex'] = $regex['sccInput3'];
				$data['matchtype'] = "scczxInput";
				break;
			case "22":
				$data['panel'] = "5";
				$data['selectedregex'] = $regex['permutaions2'];
				$data['matchtype'] = "permutaions";
				break;
			case "23":
				$data['panel'] = "5";
				$data['selectedregex'] = $regex['permutaions3'];
				$data['matchtype'] = "permutaions";
				break;
			case "24":
				$data['panel'] = "5";
				$data['selectedregex'] = $regex['combine3'];
				$data['matchtype'] = "combine";
				break;
			case "25":
				$data['panel'] = "0,1";
				$data['selectedregex'] = $regex['allSelect4'];
				$data['matchtype'] = "allSelect";
				break;
			case "26":
				$data['panel'] = "";
				$data['selectedregex'] = $regex['sccInput4'];
				$data['matchtype'] = "sccInput";
				break;
			case "27":
				$data['panel'] = "3,4";
				$data['selectedregex'] = $regex['allSelect4'];
				$data['matchtype'] = "allSelect";
				break;
			case "28":
				$data['panel'] = "";
				$data['selectedregex'] = $regex['sccInput4'];
				$data['matchtype'] = "sccInput";
				break;
			case "29":
				$data['panel'] = "0,1,2,3,4";
				$data['selectedregex'] = $regex['allSelect4'];
				$data['matchtype'] = "allSelect";
				break;
			case "30":
				$data['panel'] = "";
				$data['selectedregex'] = $regex['sccInput2'];
				$data['matchtype'] = "sccWeiInput";
				break;
			case "31":
				$data['panel'] = "5";
				$data['selectedregex'] = $regex['combine2'];
				$data['matchtype'] = "combineTwo";
				break;
			case "32":
				$data['panel'] = "5";
				$data['selectedregex'] = $regex['sccInput4'];
				$data['matchtype'] = "sccInput";
				break;
			case "33":
				$data['panel'] = "5";
				$data['selectedregex'] = $regex['combine2'];
				$data['matchtype'] = "combineTwo";
				break;
			case "34":
				$data['panel'] = "5";
				$data['selectedregex'] = $regex['sccInput4'];
				$data['matchtype'] = "sccInput";
				break;
			case "35":
				$data['panel'] = "5";
				$data['selectedregex'] = $regex['combine2'];
				$data['matchtype'] = "combine";
				break;
			case "36":
				$data['panel'] = "5";
				$data['selectedregex'] = $regex['combine2'];
				$data['matchtype'] = "combine";
				break;
			case "37":
				$data['panel'] = "0,1,2,3,4";
				$data['selectedregex'] = $regex['allSelect1'];
				$data['matchtype'] = "allSelectDw";
				break;
			case "38":
				$data['panel'] = "6";
				$data['selectedregex'] = $regex['combine2'];
				$data['matchtype'] = "combineBdw";
				break;
			case "39":
				$data['panel'] = "6";
				$data['selectedregex'] = $regex['combine2'];
				$data['matchtype'] = "combineBdw";
				break;
			case "40":
				$data['panel'] = "6";
				$data['selectedregex'] = $regex['combine2'];
				$data['matchtype'] = "combineBdw";
				break;
			case "41":
				$data['panel'] = "6";
				$data['selectedregex'] = $regex['permutaions2'];
				$data['matchtype'] = "permutaions";
				break;
			case "42":
				$data['panel'] = "7,8";
				$data['selectedregex'] = '';
				$data['matchtype'] = "allSelectDs";
				break;
			case "43":
				$data['panel'] = "10,11";
				$data['selectedregex'] = '';
				$data['matchtype'] = "allSelectDs";
				break;
			case "44":
				$data['panel'] = "7,8,9,10,11";
				$data['selectedregex'] = '';
				$data['matchtype'] = "allSelectDs";
				break;
			case "142":
				$data['panel'] = "6";
				$data['selectedregex'] = $regex['combine2'];
				$data['matchtype'] = "combineTwo";
				break;
			case "143":
				$data['panel'] = "6";
				$data['selectedregex'] = $regex['combine2'];
				$data['matchtype'] = "combineTwo";
				break;
		}
		$data['info'] = $playInfo['info'].$playInfo['example'];
		$data['num'] = $playInfo['selectNum'];
		echo json_encode($data);
		exit();
	}
	
	//彩票投注
	public function postCodeOp(){
// 		print_r($_POST);
		$time = time();
		$urlshang = $_SERVER['HTTP_REFERER']; //上一页URL     
		$urldan = $_SERVER['SERVER_NAME']; //本站域名
		$urlcheck=substr($urlshang,7,strlen($urldan));
		if($urlcheck<>$urldan){

			Re_json_encode('-100','投注不成功！原因:数据异常!');

		}

		if($_SESSION['uid']){
				$json = array();
				$amount=0; //总金额
				$bettingList =  htmlspecialchars_decode($_POST['bettingList']);
				
// 				print_r($bettingList);
				$liqType=102;
				$info='投注';//不支持追号
				$bettingListArr0 = json_decode($bettingList,true);
// 				print_r($bettingListArr0);
				$bettingListArr = $bettingListArr0[0];


				// if($this->settings['switchBuy']==0) throw new Exception('本平台已经停止购买！');
				// if($this->settings['switchDLBuy']==0 && $this->user['type'])  throw new Exception('代理不能买单！');
				if(empty($bettingListArr['selNums'])) Re_json_encode('-100','请先选择号码再提交投注');

				$type = intval($_POST['lotteryId']);
				 //检查时间 期数
				$model_data	= Model('data_class');
				$model_play = Model("played");
				$stopTime=$model_data->getGameStopTime($type);  	//封单时间
				$actionTime=$model_data->getGameActionTime($type);  //当期时间
				$actionNo=$model_data->getGameActionNo($type);  	//当期期数
// 				print_r($_POST['curIssueNum']);
// 				print_r($actionNo);
				$para['actionNo'] = $_POST['curIssueNum'];
				$para['type'] = $_POST['lotteryId'];
				$actionNo = date('Ymd',$time).'-'.sprintf("%03d",$actionNo);

				// if($actionTime!=$para['kjTime'])  throw new Exception('投注失败：你投注第'.$para['actionNo'].'已过购买时间');
				 if($actionNo!=$para['actionNo']) Re_json_encode('-100','投注失败：你投注第'.$para['actionNo'].'已过购买时间');
				 if($stopTime < $time) Re_json_encode('-100','投注失败：你投注第'.$para['actionNo'].'已过购买时间。');
// 				print_r($actionNo);
// 				print_r($para);
// 				print_r($stopTime);
				$model_bat	= Model('bat');
				// 查检每注的赔率是否正常
				$playeds = $model_bat->getPlayeds();
				
					$played=$playeds[$bettingListArr['betTypeId']];
// 					print_r($played);
// 					print_r($playeds);exit;
					//检查开启
					//if(!$played['enable'])  Re_json_encode('-100','游戏玩法组已停,请刷新再投');

					// //检查赔率
					// $chkBonus=($played['bonusProp']-$played['bonusPropBase'])/$this->settings['fanDianMax']*$this->user['fanDian']+$played['bonusPropBase']-($played['bonusProp']-$played['bonusPropBase'])*$code['fanDian']/$this->settings['fanDianMax'];//实际奖金
					// if($code['bonusProp']>$played['bonusProp']) throw new Exception('提交数据出错，请重新投注2');
					// if($code['bonusProp']<$played['bonusPropBase']) throw new Exception('提交数据出错，请重新投注3');
					// if(intval($chkBonus)!=intval($code['bonusProp'])) throw new Exception('提交数据出错，请重新投注4');
					// //检查返点
					// if(floatval($code['fanDian'])>floatval($this->user['fanDian']) || floatval($code['fanDian'])>floatval($this->settings['fanDianMax'])) throw new Exception('提交数据出错，请重新投注5');
					// //检查倍数
					// if(intval($code['beiShu'])<1) throw new Exception('倍数只能为大于1正整数');
					// // 检查注数
					// if($betCountFun=$played['betCountFun']){
					// 	if($played['betCountFun']=='descar'){
					// 		if($code['actionNum']>Bet::$betCountFun($code['actionData'])) throw new Exception('提交数据出错，请重新投注');
					// 	}else if($played['betCountFun']=='descar2'){
					// 		if($code['actionNum']<1) throw new Exception('提交数据出错，请重新投注6');
					// 	}else{
					// 		if($code['actionNum']!=Bet::$betCountFun($code['actionData'])) throw new Exception('提交数据出错，请重新投注7');
					// 	}
					// }///end

				$model_member	= Model('member');
				$member_info = $model_member->getMemberInfo(array('uid' =>$_SESSION['uid']),'coin');
				//查询可用金额
				$amount = $bettingListArr['totalBetting']*$bettingListArr['unitPrice'];
					if($member_info['coin'] < $amount){

						Re_json_encode('-100','投注不成功！原因:游戏分数不够本次投注,请先充值!');
					}
				
				try {

			    $model_bat->beginTransaction();

			    // 插入投注表
				$param['actionData']		=$bettingListArr['selNums'];					//投注号码
				$param['fanDian']			=0;												//返点
				$param['bonusProp']			=floatval($bettingListArr['bonusProp']);		//奖金比例
				$param['beiShu']			=intval($bettingListArr['totalBeishu']);		//投注倍数
				$param['orderId']			=intval(rand(10000000000,99999999999));			//订单号

				$param['weiShu']			=intval(0);										//附加位数
				$param['playedId']			=intval($bettingListArr['ruleId']);				//玩法ID
				$param['playedGroup']		=intval($bettingListArr['betTypeId']);			//玩法组ID
				$param['type']				=intval($type); 								//投注种类

				$param['wjorderId']			=$param['type'].$param['playedId'].$this->randomkeys(8-strlen($param['type'].$param['playedId']));	//随机订单号
				$param['actionNum']			=abs($bettingListArr['totalBetting']);			//投注注数
				$param['mode']				=abs(2);
				$param['uid']				=$_SESSION['uid'];
				$param['username']			=$_SESSION['username'];
				$param['actionTime']   		=$time;
				$param['actionNo']			=$actionNo;										//投注期号
				$param['kjTime']			=$actionTime;									//开奖时间
				$param['actionIP']			=getIp();										//投注IP
				$param['serializeId']		=uniqid();										//投注号

				$amount=abs($bettingListArr['totalBetting']*$bettingListArr['unitPrice']*$bettingListArr['totalBeishu']);

				$r = $model_bat->add($param);
		
				$playinfo = $model_play->getPlayInfo(array('id'=>$param['playedId']));
			  	if($r){

					// 添加用户资金流动日志
					$model_bat->addCoin(array(
						'uid'=>$_SESSION['uid'],
						'type'=>$param['type'],								//彩票类型
						'playedId'=>$param['playedId'],						//玩法ID
						'actionIP'=>getIp(),
						'liqType'=>$liqType,								//资金流动类型
						'info'=>$info,										//资金流动说明
						'extfield0'=>$r,									//订单ID
						'extfield1'=>'重庆彩|'.$playinfo['name'].'|'.$param['actionNo'],		//游戏|玩法|期号				
						'extfield2'=>$param['wjorderId'],					//随机订单号
						'coin'=>-$amount,									//剩余可用流动资金
						'fcoin'=>$amount,									//流动冻结资金
					));

					$user_model = Model('member');
					$userinfo = $user_model->getMemberInfo(array('uid'=>$_SESSION['uid']));
					$_SESSION['coin']	= $userinfo['coin'];
					$model_bat->commit();
			  		echo ('{"infoList":[{"Key":"0,","Value":"投注成功"}],"useInfo":{"GamePoint":"'.$userinfo['coin'].'","AvailablePoint":"'.$userinfo['score'].'","FreezePoint":"'.$userinfo['fcoin'].'"}}');
			  		exit();
			  	}else{

			  		Re_json_encode('-100','投注不成功！原因:未知信息!');
			  	}
				
			 
			} catch (Exception $e) {
			    $model_bat->rollback();
	            Re_json_encode('-100','投注不成功！原因:未知信息!');
			}
		}
	}
	
	//ajax撤单
	public function deleteCodeOp(){
		$wjorderId = $_POST['orderId'];
		$typeId = $_POST['lotteryId'];
		
		$model_bat	= Model('bat');
		$model_type = Model('kjtype');
		$model_play = Model("played");
		
		$bets = $model_bat->getBetInfo(array('wjorderId'=>$wjorderId));
		$typeInfo = $model_type->getTypeInfo(array('id'=>$typeId));
		
		$playinfo = $model_play->getPlayInfo(array('id'=>$bets['playedId']));
		try{
			$model_bat->beginTransaction();
			if(!$bets) $data = "找不到订单";
			elseif($bets['isDelete']) $data = "该订单已撤单。";
			elseif($bets['uid']!=$_SESSION['uid']) $data = "改订单不是您的，您不能撤单。";			// 可考虑管理员能给用户撤单情况
			elseif($bets['kjTime']<=time()) $data = "已经开奖，不能撤单。";
			elseif($bets['qz_uid']) $data = "该订单已经被人抢庄，不能撤单。";
			
			// 冻结时间后不能撤单
			elseif($bets['kjTime']-$typeInfo['data_ftime'] < time()) $data = "订单已结冻，不能撤单。";			
			else{
				$amount=$bets['beiShu'] * $bets['mode'] * $bets['actionNum'];
				$amount=abs($amount);
				// 添加用户资金变更日志
				$model_bat->addCoin(array(
						'uid'=>$bets['uid'],
						'type'=>$bets['type'],
						'playedId'=>$bets['playedId'],
						'liqType'=>7,
						'info'=>"撤单",
						'extfield0'=>$bets['id'],
						'extfield1'=>'重庆彩|'.$playinfo['name'].'|'.$bets['actionNo'],
						'extfield2'=>$bets['wjorderId'],
						'coin'=>$amount,
						'fcoin'=>-$amount
				));
					
				// 更改定单为已经撤单状态
				$updateid = $model_bat->updateBets(array('isDelete'=>1),$bets['id']);
				if($updateid) $data = "撤单成功。";
				$model_bat->commit();
			}
		}catch(Exception $e){
			$model_bat->rollback();
			$data = "撤单失败。";
		}
		
		echo json_encode($data);
		exit();
		
	}

}
